package com.plian.system.service.hr.recruitment.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.plian.Tools.CollectionUtil;
import com.plian.Tools.DateUtil;
import com.plian.Tools.StringUtil;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.entity.hr.recruitment.PartTimeInfo;
import com.plian.system.entity.hr.recruitment.PartTimeManagement;
import com.plian.system.entity.sys.Dict;
import com.plian.system.enumeratea.PartTimeStatus;
import com.plian.system.mapper.hr.recruitment.PartTimeInfoMapper;
import com.plian.system.mapper.hr.recruitment.PartTimeManagementMapper;
import com.plian.system.mapper.hr.staff.StaffFilesMapper;
import com.plian.system.mapper.sys.DictMapper;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.pdf.OutPdf;
import com.plian.system.service.bt.baseinfo.BaseInfoService;
import com.plian.system.service.hr.recruitment.INewPartTimeManagementService;
import com.plian.system.service.hr.recruitment.IPartTimeInfoService;
import com.plian.system.service.hr.staff.IStaffFilesService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.sys.orgzation.OrgzationService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.hr.recruitment.PartTimeManagementVO;
import com.plian.system.wrapper.hr.recruitment.PartTimeManagementWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author BladeX
 * @since 2019-12-02
 */
@Slf4j
@Service
@AllArgsConstructor
public class NewPartTimeManagementServiceImpl extends BaseServiceImpl<PartTimeManagementMapper, PartTimeManagement> implements INewPartTimeManagementService
//        , BaseFlowService
{


    private IStaffFilesService staffFilesService;

    private FormWorkflowService formWorkflowService;

    private OrgzationService orgzationService;

    private BaseInfoService baseInfoService;

    private OrgzationDao orgzationDao;

    private IPartTimeInfoService partTimeInfoService;

    private PartTimeInfoMapper partTimeInfoMapper;

    private IFormCodeService formCodeService;

    private FileService fileService;

    private PartTimeManagementWrapper partTimeManagementWrapper;

    private final DictMapper dictMapper;

    private final StaffFilesMapper staffFilesMapper;

    private final IOrgService orgService;

    private IApprovalMessageService approvalMessageService;



//    //名称转cod 用参照字典（参照key,<name,id>）(需确保每个名字唯一) TODO DEL
//    private static HashMap<String, Map<String, String>> nameMap = new HashMap<>();
//
//    @Override
//    public boolean saveOrUpdate(PartTimeManagement partTimeManagement) {
//
//        boolean flag = false;
//        if (partTimeManagement.getId() == null) {
//            partTimeManagement.setVersion("1");
//            if (partTimeManagement.getStatus() == null) {
//                partTimeManagement.setStatus(FormStatusConstant.UNREVIEWED);
//            }
//            partTimeManagement.setCode(formCodeService.getCode(FormTypeConstant.HR_PART_TIME_FORM));
//            partTimeManagement.setFormType(String.valueOf(FormTypeConstant.HR_PART_TIME_FORM));
//            flag = true;
//        }
//        boolean result = super.saveOrUpdate(partTimeManagement);
//        if (flag) {
//            fileService.saveAll(String.valueOf(partTimeManagement.getId()), partTimeManagement.getDocList());
//        } else {
//            fileService.edit(String.valueOf(partTimeManagement.getId()), partTimeManagement.getDocList());
//        }
//
//        return result;
//    }
//
//    @Override
//    public boolean deleteLogic(List<Long> ids) {
//        for (Long id : ids) {
//            PartTimeManagement partTimeManagement = getById(id);
//            if (partTimeManagement == null) {
//                return false;
//            } else if (partTimeManagement.getStatus() != null &&
//                    (partTimeManagement.getStatus() != FormStatusConstant.STASH && partTimeManagement.getStatus() != FormStatusConstant.UNREVIEWED)) {
//                return false;
//            }
//            formWorkflowService.deleteProcessInstance(String.valueOf(id));
//        }
//
//        boolean result = super.deleteLogic(ids);
//        if (result) {
//            partTimeInfoService.deleteLogicPartTimeManagementId(ids);
//        }
//        return result;
//    }
//
//    @Override
//    public HashMap<String, Object> commit(String id) {
//        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW, "提交");
//        //将需要提交的流程变量返回，用于工作流侧
//        return new HashMap<String, Object>();
//    }
//
//    @Override
//    public Boolean finish(String id) {
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH, "审批完成");
//    }
//
//    @Override
//    public Boolean reject(String id, int formState, String comment) {
//        return handleStatus(Long.valueOf(id), formState, comment);
//    }
//
//    /**
//     * 统一处理状态机事件方法
//     *
//     * @param id           主键
//     * @param updateStatus 更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus, String comment) {
//        try {
//            PartTimeManagement partTimeManagement = getById(id);
//            /**
//             * 设置审批人和审批时间
//             */
//            if (updateStatus == FormStatusConstant.FINISH) {
//                partTimeManagement.setApprovedUser(TokenUtil.getTokenUserId());
//                Date now = DateUtil.now();
//                partTimeManagement.setApprovedTime(now);
//                partTimeInfoService.changeStatus(id, PartTimeStatus.INCUMBENCY.getStatus());
//
//                if (StringUtil.isBlank(partTimeManagement.getFilingCode())) {
//                    partTimeManagement.setFilingCode("兼企" + formCodeService.getFilingCode(FormTypeConstant.HR_PART_TIME_FORM));
//                }
//            }
//            partTimeManagement.setStatus(updateStatus);
//
//            if (YthConstant.DATA_NINGBO.equals(partTimeManagement.getDataSource())) {
//                if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT) {
//                    ApprovalMessage approvalMessage = new ApprovalMessage();
//                    approvalMessage.setDataSourceId(partTimeManagement.getDataSourceId());
//                    approvalMessage.setOpinion(comment);
//                    approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
//                    approvalMessage.setIsSend(1);
//                    approvalMessage.setFilingCode(partTimeManagement.getFilingCode());
//                    approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
//                    approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
//                    approvalMessage.setFormType(Integer.valueOf(partTimeManagement.getFormType()));
//                    approvalMessageService.save(approvalMessage);
//                }
//            }
//            updateById(partTimeManagement);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//
//    @Override
//    public File buildpdf(Long id, Integer type) {
//        File file = null;
//        try {
//            PartTimeManagement partTimeManagement = getById(id);
//            if (partTimeManagement != null && !"".equals(partTimeManagement)) {
//                PartTimeManagementVO partTimeManagementVO = partTimeManagementWrapper.entityToVO(partTimeManagement);
//                Map<String, Object> data = new HashMap<String, Object>();
//                data.putAll(OutPdf.beanToMap(partTimeManagementVO));
//                String birthday = (String) data.get("birthday").toString().substring(0, 10);
//                data.put("birthday", birthday);
//                ResourceLoader resourceLoader = new DefaultResourceLoader();
//
//                File model = File.createTempFile("logo", ".pdf");
//                try {
//                    if (type == 1) {
//                        FileUtils.copyInputStreamToFile(resourceLoader.getResource("/pdf/personnel_part_time_management.pdf").getInputStream(), model);
//                    } else {
//                        FileUtils.copyInputStreamToFile(resourceLoader.getResource("/pdf/personnel_part_time_management2.pdf").getInputStream(), model);
//                    }
//
//                } finally {
//                    //关闭IO
//                    //IOUtils.closeQuietly(inputStream);
//                }
//                String fileName = model.getPath();
//                PdfReader reader = new PdfReader(fileName);
//                ByteArrayOutputStream bos = new ByteArrayOutputStream();
//                /* 将要生成的目标PDF文件名称 */
//                PdfStamper ps = new PdfStamper(reader, bos);
//                /* 使用中文字体 */
//                BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//                ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
//                fontList.add(bf);
//
//                /* 取出报表模板中的所有字段 */
//                AcroFields fields = ps.getAcroFields();
//                fields.setSubstitutionFonts(fontList);
//                for (String key : data.keySet()) {
//                    String value = data.get(key).toString();
//                    if (data.get(key) instanceof Date) {
//                        value = processDate((Date) data.get(key));
//                    }
//                    fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
//                }
//                //民族
//                Dict nationDict = dictMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getCode, partTimeManagement.getNationId()));
//                fields.setField("nation", nationDict.getName());
//                //健康状况
//                Dict healthConditionDict = dictMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getCode, partTimeManagement.getHealthConditionId()));
//                fields.setField("healthCondition", healthConditionDict.getName());
//                //全职学位
//                fields.setField("fulltimeDegree", partTimeManagement.getFulltimeDegree());
//                fields.setField("fulltimeSchoolMajor", partTimeManagement.getFulltimeSchoolMajor());
//                //在职学位
//                fields.setField("onjobDegree", partTimeManagement.getOnjobDegree());
//                fields.setField("onjobSchoolMajor", partTimeManagement.getOnjobSchoolMajor());
//
//                List<PartTimeInfo> allPartTimeInfos = partTimeInfoMapper.selectList(new LambdaQueryWrapper<PartTimeInfo>().eq(PartTimeInfo::getStaffNameId, partTimeManagement.getStaffNameId()));
//
//                if (CollectionUtil.isNotEmpty(allPartTimeInfos)) {
//                    /**
//                     * 已兼职情况
//                     */
//                    List<PartTimeInfo> yjzPartTimeInfos = allPartTimeInfos.stream().filter(item ->
//                            item.getStatus().equals(PartTimeStatus.INCUMBENCY.getStatus())).collect(Collectors.toList());
//                    if (CollectionUtil.isNotEmpty(yjzPartTimeInfos)) {
//                        StringBuffer sb = new StringBuffer();
//                        yjzPartTimeInfos.forEach(item -> {
//                            if (StringUtils.isNotEmpty(item.getPartTimeEnterpriseName())) {
//                                sb.append(item.getPartTimeEnterpriseName() + "  ");
//                            }
//                            if (StringUtils.isNotEmpty(item.getProposedConcurrentPost())) {
//                                sb.append(item.getProposedConcurrentPost());
//                            }
//                            sb.append("\n");
//                        });
//                        //已兼职情况
//                        fields.setField("parttimeJobSituation", sb.toString());
//
//                        //意见
//                        fields.setField("companyPartyOrgOpinion", yjzPartTimeInfos.get(0).getCompanyPartyOrgOpinion());
//                        fields.setField("approvedOpinion", yjzPartTimeInfos.get(0).getApprovedOpinion());
//                        fields.setField("gzRegulationOpinion", yjzPartTimeInfos.get(0).getGzRegulationOpinion());
//                    }
//
//                    /**
//                     * 拟兼职情况
//                     */
//                    List<PartTimeInfo> partTimeInfos = allPartTimeInfos.stream().filter(item
//                            -> item.getStatus().equals(PartTimeStatus.AUDIT.getStatus())).collect(Collectors.toList());
//                    if (CollectionUtil.isNotEmpty(partTimeInfos)) {
//                        String partTimeJobTimeStr = "";
//                        String proposedConcurrentPost = "";
//                        String parttimeJobReason = "";
//                        for (PartTimeInfo partTimeInfo : partTimeInfos) {
//                            if (Optional.ofNullable(partTimeInfo.getPartTimeStartTime()).isPresent() && Optional.ofNullable(partTimeInfo.getPartTimeEndTime()).isPresent()) {
//                                String startStr = DateUtil.formatDate(partTimeInfo.getPartTimeStartTime());
//                                String endStr = DateUtil.formatDate(partTimeInfo.getPartTimeEndTime());
//                                if (StringUtil.isBlank(partTimeJobTimeStr)) {
//                                    partTimeJobTimeStr += startStr + "~" + endStr;
//                                } else {
//                                    partTimeJobTimeStr += "，" + startStr + "~" + endStr;
//                                }
//                            }
//
//                            if (Optional.ofNullable(partTimeInfo.getPartTimeEnterpriseName()).isPresent() && Optional.ofNullable(partTimeInfo.getProposedConcurrentPost()).isPresent()) {
//                                if (StringUtil.isBlank(proposedConcurrentPost)) {
//                                    proposedConcurrentPost += partTimeInfo.getPartTimeEnterpriseName() + partTimeInfo.getProposedConcurrentPost();
//                                } else {
//                                    proposedConcurrentPost += "，" + partTimeInfo.getPartTimeEnterpriseName() + partTimeInfo.getProposedConcurrentPost();
//                                }
//                            }
//
//                            if (Optional.ofNullable(partTimeInfo.getPartTimeJobReason()).isPresent()) {
//                                if (StringUtil.isBlank(parttimeJobReason)) {
//                                    parttimeJobReason += partTimeInfo.getPartTimeJobReason();
//                                } else {
//                                    parttimeJobReason += "，" + partTimeInfo.getPartTimeJobReason();
//                                }
//                            }
//
//                        }
//                        fields.setField("proposedConcurrentPost", proposedConcurrentPost);
//                        fields.setField("parttimeJobTime", partTimeJobTimeStr);
//                        fields.setField("parttimeJobReason", parttimeJobReason);
//
//                        //意见
//                        fields.setField("companyPartyOrgOpinion", partTimeInfos.get(0).getCompanyPartyOrgOpinion());
//                        fields.setField("approvedOpinion", partTimeInfos.get(0).getApprovedOpinion());
//                        fields.setField("gzRegulationOpinion", partTimeInfos.get(0).getGzRegulationOpinion());
//                    }
//                }
//
//                ps.setFormFlattening(true);
//                ps.close();
//                File dir = new File(model.getParent());
//                file = File.createTempFile("part_time_management", ".pdf", dir);
//                OutputStream fos = new FileOutputStream(file);
//                fos.write(bos.toByteArray());
//                fos.flush();
//                fos.close();
//                bos.close();
//            }
//
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return file;
//    }
//
//
    private static String processDate(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
        return date == null ? "" : formatter.format(date);
    }
//
//
//    @Override
//    public File nextPdf(PartTimeManagement partTimeManagement) {
//        File file = null;
//        try {
//            if (partTimeManagement != null && !"".equals(partTimeManagement)) {
//                PartTimeManagementVO partTimeManagementVO = partTimeManagementWrapper.entityToVO(partTimeManagement);
//                Map<String, Object> data = new HashMap<String, Object>();
//                data.putAll(OutPdf.beanToMap(partTimeManagementVO));
//                String birthday = (String) data.get("birthday").toString().substring(0, 10);
//                data.put("birthday", birthday);
//                ResourceLoader resourceLoader = new DefaultResourceLoader();
//                File model = File.createTempFile("logo", ".pdf");
//
//                if (partTimeManagement.getType() == 1) {
//                    FileUtils.copyInputStreamToFile(resourceLoader.getResource("/pdf/personnel_part_time_management.pdf").getInputStream(), model);
//                } else {
//                    FileUtils.copyInputStreamToFile(resourceLoader.getResource("/pdf/personnel_part_time_management2.pdf").getInputStream(), model);
//                }
//                String fileName = model.getPath();
//                PdfReader reader = new PdfReader(fileName);
//                ByteArrayOutputStream bos = new ByteArrayOutputStream();
//                /* 将要生成的目标PDF文件名称 */
//                PdfStamper ps = new PdfStamper(reader, bos);
//                /* 使用中文字体 */
//                BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//                ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
//                fontList.add(bf);
//
//                /* 取出报表模板中的所有字段 */
//                AcroFields fields = ps.getAcroFields();
//                fields.setSubstitutionFonts(fontList);
//                for (String key : data.keySet()) {
//                    String value = data.get(key).toString();
//                    if (data.get(key) instanceof Date) {
//                        value = processDate((Date) data.get(key));
//                    }
//                    fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
//                }
//                //民族
//                Dict nationDict = dictMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getCode, partTimeManagement.getNationId()));
//                fields.setField("nation", nationDict.getName());
//                //健康状况
//                Dict healthConditionDict = dictMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getCode, partTimeManagement.getHealthConditionId()));
//                fields.setField("healthCondition", healthConditionDict.getName());
//                //全职学位
//                fields.setField("fulltimeDegree", partTimeManagement.getFulltimeDegree());
//                fields.setField("fulltimeSchoolMajor", partTimeManagement.getFulltimeSchoolMajor());
//                //在职学位
//                fields.setField("onjobDegree", partTimeManagement.getOnjobDegree());
//                fields.setField("onjobSchoolMajor", partTimeManagement.getOnjobSchoolMajor());
//
//                /**
//                 * 已兼职情况
//                 */
//                List<PartTimeInfo> yjzPartTimeInfos = partTimeManagement.getPartTimeInfos();
//                if (CollectionUtil.isNotEmpty(yjzPartTimeInfos)) {
//                    StringBuffer sb = new StringBuffer();
//                    yjzPartTimeInfos.forEach(item -> {
//                        if (StringUtils.isNotEmpty(item.getPartTimeEnterpriseName())) {
//                            sb.append(item.getPartTimeEnterpriseName() + "  ");
//                        }
//                        if (StringUtils.isNotEmpty(item.getProposedConcurrentPost())) {
//                            sb.append(item.getProposedConcurrentPost());
//                        }
//                        sb.append("\n");
//                    });
//                    //已兼职情况
//                    fields.setField("parttimeJobSituation", sb.toString());
//
//                    //意见
//                    fields.setField("companyPartyOrgOpinion", yjzPartTimeInfos.get(0).getCompanyPartyOrgOpinion());
//                    fields.setField("approvedOpinion", yjzPartTimeInfos.get(0).getApprovedOpinion());
//                    fields.setField("gzRegulationOpinion", yjzPartTimeInfos.get(0).getGzRegulationOpinion());
//                }
//                /**
//                 * 拟兼职
//                 */
//                List<PartTimeInfo> njzPartTimeInfos = partTimeManagementVO.getNjzPartTimeInfos();
//                if (CollectionUtil.isNotEmpty(njzPartTimeInfos)) {
//                    String partTimeJobTimeStr = "";
//                    String proposedConcurrentPost = "";
//                    String parttimeJobReason = "";
//                    for (PartTimeInfo partTimeInfo : njzPartTimeInfos) {
//                        if (Optional.ofNullable(partTimeInfo.getPartTimeStartTime()).isPresent() && Optional.ofNullable(partTimeInfo.getPartTimeEndTime()).isPresent()) {
//                            String startStr = DateUtil.formatDate(partTimeInfo.getPartTimeStartTime());
//                            String endStr = DateUtil.formatDate(partTimeInfo.getPartTimeEndTime());
//                            //拟兼职时间
//                            if (StringUtil.isBlank(partTimeJobTimeStr)) {
//                                partTimeJobTimeStr += startStr + "~" + endStr;
//                            } else {
//                                partTimeJobTimeStr += "，" + startStr + "~" + endStr;
//                            }
//                        }
//
//                        if (Optional.ofNullable(partTimeInfo.getPartTimeEnterpriseName()).isPresent() && Optional.ofNullable(partTimeInfo.getProposedConcurrentPost()).isPresent()) {
//                            //拟兼职职务
//                            if (StringUtil.isBlank(proposedConcurrentPost)) {
//                                proposedConcurrentPost += partTimeInfo.getPartTimeEnterpriseName() + partTimeInfo.getProposedConcurrentPost();
//                            } else {
//                                proposedConcurrentPost += "，" + partTimeInfo.getPartTimeEnterpriseName() + partTimeInfo.getProposedConcurrentPost();
//                            }
//                        }
//
//                        if (Optional.ofNullable(partTimeInfo.getPartTimeJobReason()).isPresent()) {
//                            //拟兼职理由
//                            if (StringUtil.isBlank(parttimeJobReason)) {
//                                parttimeJobReason += partTimeInfo.getPartTimeJobReason();
//                            } else {
//                                parttimeJobReason += "，" + partTimeInfo.getPartTimeJobReason();
//                            }
//                        }
//
//                    }
//                    //拟兼任职务
//                    fields.setField("proposedConcurrentPost", proposedConcurrentPost);
//                    //拟兼职时间
//                    fields.setField("parttimeJobTime", partTimeJobTimeStr);
//                    //拟兼职理由
//                    fields.setField("parttimeJobReason", parttimeJobReason);
//
//                    //意见
//                    fields.setField("companyPartyOrgOpinion", njzPartTimeInfos.get(0).getCompanyPartyOrgOpinion());
//                    fields.setField("approvedOpinion", njzPartTimeInfos.get(0).getApprovedOpinion());
//                    fields.setField("gzRegulationOpinion", njzPartTimeInfos.get(0).getGzRegulationOpinion());
//
//                }
//                /* 必须要调用这个，否则文档不会生成的 */
//                ps.setFormFlattening(true);
//                ps.close();
//                File dir = new File(model.getParent());
//                file = File.createTempFile("part_time_management", ".pdf", dir);
//                OutputStream fos = new FileOutputStream(file);
//                fos.write(bos.toByteArray());
//                fos.flush();
//                fos.close();
//                bos.close();
//            }
//
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return file;
//    }
//
//
//    @Override
//    public PartTimeManagementVO setChild(PartTimeManagementVO partTimeManagementVO) {
//        if (!Optional.ofNullable(partTimeManagementVO).isPresent()) {
//            return null;
//        }
//        QueryWrapper<PartTimeInfo> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("part_time_management_id", partTimeManagementVO.getId());
//        List<PartTimeInfo> partTimeInfos = partTimeInfoService.list(queryWrapper);
//        partTimeManagementVO.setPartJobSituation(partTimeInfos);
//
//        return partTimeManagementVO;
//    }
//
//    @Override
//    public List<PartTimeManagement> selectExpired() {
//        return baseMapper.selectExpired();
//    }
//
//    @Override
//    public ObjResult getDetailObj(PartTimeManagementVO partTimeManagementVO) {
//        if (!Optional.ofNullable(partTimeManagementVO).isPresent()) {
//            return new ObjResult(CommonCode.FAIL);
//        }
//
//        PageData pd = new PageData();
//        ObjectMapper mapper = new ObjectMapper();
//        String json = JSON.toJSONStringWithDateFormat(partTimeManagementVO, DateUtil.PATTERN_DATETIME);
//        try {
//            pd.putAll(mapper.readValue(json, new TypeReference<HashMap<String, String>>() {
//            }));
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return new ObjResult(CommonCode.ERROR);
//        }
//        //拟兼职
//        pd.put("njzPartTimeInfos",
//                partTimeInfoService.list(new QueryWrapper<PartTimeInfo>().eq("part_time_management_id", partTimeManagementVO.getId())
//                        .eq("status", PartTimeStatus.AUDIT.getStatus())).stream().collect(Collectors.toList())
//        );
//        //已兼任
//        pd.put("partTimeInfos", selectPartTimeInfoStatus(partTimeManagementVO.getStaffNameId(), PartTimeStatus.INCUMBENCY.getStatus()));
//
//        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
//        objResult.setPageData(pd);
//        return objResult;
//    }
//
//    /**
//     * 已兼职情况
//     *
//     * @param staffNameId
//     * @return
//     */
//    public List<PartTimeInfo> selectPartTimeInfoStatus(Long staffNameId, Integer status) {
//        List<PartTimeInfo> partTimeInfos = partTimeInfoMapper.selectList(new LambdaQueryWrapper<PartTimeInfo>()
//                .eq(PartTimeInfo::getStaffNameId, staffNameId).eq(PartTimeInfo::getStatus, status));
//        if (status.equals(PartTimeStatus.INCUMBENCY.getStatus())) {
//            //处理字端当前是否兼职
//            Date date = new Date();
//            partTimeInfos.forEach(item -> {
//                if (item.getPartTimeEndTime() != null && item.getPartTimeEndTime() != null) {
//                    if (item.getPartTimeEndTime().getTime() >= date.getTime() && item.getPartTimeStartTime().getTime() < date.getTime()) {
//                        item.setNowPartTimeStatus(0);
//                    } else {
//                        item.setNowPartTimeStatus(1);
//                    }
//                }
//            });
//        }
//        return partTimeInfos;
//    }
//
//
//    @Override
//    @Transactional(rollbackFor = RuntimeException.class)
//    public Boolean submit(PartTimeManagement partTimeManagement) {
//        boolean result = saveOrUpdate(partTimeManagement);
//        if (result) {
//            List<PartTimeInfo> nJzPartTimeInfos = partTimeManagement.getNjzPartTimeInfos();
//            if (CollectionUtil.isNotEmpty(nJzPartTimeInfos)) {
//                for (PartTimeInfo partTimeInfo : nJzPartTimeInfos) {
//                    if (partTimeInfo.getId() != null &&
//                            Optional.ofNullable(partTimeInfo.getIsDeleted()).isPresent() && partTimeInfo.getIsDeleted().intValue() == 1) {
//                        partTimeInfoService.removeById(partTimeInfo.getId());
//                    } else {
//                        partTimeInfo.setPartTimeManagementId(partTimeManagement.getId());
//                        partTimeInfo.setStaffNameId(partTimeManagement.getStaffNameId());
//                        partTimeInfo.setPartTimeManagementId(partTimeManagement.getId());
//                        partTimeInfo.setStatus(PartTimeStatus.AUDIT.getStatus());
//                        partTimeInfoService.saveOrUpdate(partTimeInfo);
//                    }
//                }
//            }
//        }
//
//        return result;
//    }
//
//    @Override
//    public String checkSubmit(PartTimeManagement partTimeManagement) {
//        if (Optional.ofNullable(partTimeManagement).isPresent()) {
//            if (CollectionUtil.isEmpty(partTimeManagement.getNjzPartTimeInfos())) {
//                return "拟兼职信息未填写";
//            }
//        }
//        return null;
//    }
//
//    @Override
//    public List<PageData> findByIds(List<String> formIds) {
//        LambdaQueryWrapper<PartTimeManagement> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.in(PartTimeManagement::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
//        List<PartTimeManagement> recruitmentManagements = list(queryWrapper);
//        List<PartTimeManagementVO> recruitmentManagementVOS = partTimeManagementWrapper.entityToVO(recruitmentManagements);
//        List<PageData> pageDataList = new ArrayList<>();
//        try {
//            if (CollectionUtil.isNotEmpty(recruitmentManagementVOS)) {
//                for (PartTimeManagementVO vo : recruitmentManagementVOS) {
//                    PageData pd = new PageData();
//                    pd.put("id", vo.getId());
//                    pd.put("UNITNAME", vo.getCompanyName());
//                    pd.put("APPLICANTNAME", vo.getCreateUserName());
//                    pd.put("applicantId", vo.getCreateUser());
//                    pd.put("applyOrganizationId", vo.getCompanyNameId());
//                    pd.put("formType", FormTypeConstant.HR_PART_TIME_FORM);
//                    pd.put("orgName", vo.getCompanyName());
//                    pageDataList.add(pd);
//                }
//            }
//
//            return pageDataList;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return pageDataList;
//    }
//
//    @Override
//    public List<Integer> getFormType() {
//        return Arrays.asList(FormTypeConstant.HR_PART_TIME_FORM);
//    }
//
//    @Override
//    public void goBackToStash(String formId) {
//        partTimeInfoService.changeStatus(Long.valueOf(formId), PartTimeStatus.AUDIT.getStatus());
//        handleStatus(Long.valueOf(formId), UNREVIEWED, null);
//    }
//
//
//    @Override
//    @Transactional(rollbackFor = RuntimeException.class)
//    public String savePartTimeManagementReform(String data) {
//        log.info("info:接受数字宁波兼职信息...");
//        YthResult ythResult = new YthResult();
//        //成功的id集合
//        List<String> successIds = new ArrayList<>();
//        //失败的id集合
//        List<String> failIds = new ArrayList<>();
//        //失败的原因
//        List<String> failReasons = new ArrayList<>();
//        //将json字符串转换成list
//        List<PartTimeManagement> dataList = JSON.parseArray(data, PartTimeManagement.class);
//        //判断list是否为空
//        if (CollectionUtil.isNotEmpty(dataList)) {
//            //根据datasourceIds 查询出所有的数据
//            List<PartTimeManagement> list = list(new LambdaQueryWrapper<PartTimeManagement>()
//                    .in(PartTimeManagement::getDataSourceId, dataList.stream()
//                            .map(PartTimeManagement::getDataSourceId).toArray()));
//            //如果数据库中有数据，就更新，没有就新增
//            Map<String, String> orgSourceIds = orgService.getSourceId();
//            for (PartTimeManagement entity : dataList) {
//                String dataSourceId = entity.getDataSourceId();
//                if (CollectionUtil.isNotEmpty(list)) {
//                    List<String> olIds = list.stream().map(PartTimeManagement::getDataSourceId).collect(Collectors.toList());
//                    //判断数据库中是否有数据
//                    if (olIds.contains(dataSourceId)) {
//                        for (PartTimeManagement oldEntity : list) {
//                            if (dataSourceId.equals(oldEntity.getDataSourceId())) {
//                                successIds.add(dataSourceId);
//                                entity.setId(oldEntity.getId());
//                                entity.setDataSource(YthConstant.DATA_NINGBO);
//
//                                extracted(entity);
//
//                                submit(entity);
//                                list.remove(oldEntity);
//                                break;
//                            }
//                        }
//                    } else {
//                        //如果数据库中没有数据，就新增
//                        entity.setDataSource(YthConstant.DATA_NINGBO);
//
//                        extracted(entity);
//
//                        submit(entity);
//                        successIds.add(entity.getDataSourceId());
//                    }
//                } else {
//                    entity.setDataSource(YthConstant.DATA_NINGBO);
//
//                    extracted(entity);
//
//                    submit(entity);
//                    successIds.add(entity.getDataSourceId());
//                }
//            }
//        } else {
//            failReasons.add("数据为空");
//        }
//        ythResult.setSuccessIds(successIds);
//        ythResult.setFailIds(failIds);
//        ythResult.setFailReason(StringUtils.join(failReasons, ";"));
//        //ythResult转换成json字符串
//        return JSON.toJSONString(ythResult);
//    }
//
//    /**
//     * 将数字宁波过来的数据人员id，从同步过来的人员档案中取出来，兼职主表保存入库之后的人员主键数据
//     *
//     * @param entity
//     */
//    private void extracted(PartTimeManagement entity) {
//        Map<String, String> orgSourceIds = orgService.getSourceId();
//        String orgId = orgSourceIds.get(entity.getCompanyNameId());
//        if (StringUtils.isNotBlank(orgId)) {
//            entity.setCompanyNameId(orgId);
//            entity.setCreateCompanyId(orgId);
//        }
//        StaffFiles staffFiles = staffFilesMapper.selectOne(new LambdaQueryWrapper<StaffFiles>().eq(StaffFiles::getDataSourceId, entity.getStaffNameId())
//                .eq(StaffFiles::getDataSource, 3));
//        if (Optional.ofNullable(staffFiles).isPresent()) {
//            entity.setStaffNameId(staffFiles.getId());
//        }
//
//        List<PartTimeInfo> partTimeInfos = entity.getPartTimeInfos();
//        if (CollectionUtil.isNotEmpty(partTimeInfos)) {
//            partTimeInfos.forEach(item->{
//                if (StringUtil.isNotBlank(orgId)){
//                    item.setCreateCompanyId(orgId);
//                }
//                if (Optional.ofNullable(staffFiles).isPresent()) {
//                    item.setStaffNameId(staffFiles.getId());
//                }
//            });
//
//        }
//
//
//    }

    @Override
    public File export(Long id, Integer type, HttpServletResponse response) {
        File file = null;
        try {
            PartTimeManagement partTimeManagement = getById(id);
            if (partTimeManagement != null && !"".equals(partTimeManagement)) {
                PartTimeManagementVO partTimeManagementVO = partTimeManagementWrapper.entityToVO(partTimeManagement);

                Map<String, Object> data = new HashMap<String, Object>();
                data.putAll(OutPdf.beanToMap(partTimeManagementVO));
                String birthday = data.get("birthday").toString().substring(0, 10);
                data.put("birthday", birthday);
                ResourceLoader resourceLoader = new DefaultResourceLoader();

                File model = File.createTempFile("logo", ".pdf");
                String pdfName = "";
                if (type == 1) {
                    pdfName = "企业审批表";
                    FileUtils.copyInputStreamToFile(resourceLoader.getResource("/pdf/personnel_part_time_management.pdf").getInputStream(), model);
                } else {
                    pdfName = "社会团体审批表";
                    FileUtils.copyInputStreamToFile(resourceLoader.getResource("/pdf/personnel_part_time_management2.pdf").getInputStream(), model);
                }

                String fileName = model.getPath();
                // 读取PDF模板表单
                PdfReader reader = new PdfReader(fileName);
                // 字节数组流，用来缓存文件流
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                /* 将要生成的目标PDF文件名称 */
                PdfStamper ps = new PdfStamper(reader, bos);
                /* 使用中文字体 */
                BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
                fontList.add(bf);
                /* 取出报表模板中的所有字段 */
                AcroFields fields = ps.getAcroFields();
                fields.setSubstitutionFonts(fontList);
                for (String key : data.keySet()) {
                    String value = data.get(key).toString();
                    if (data.get(key) instanceof Date) {
                        value = processDate((Date) data.get(key));
                    }
                    // 为字段赋值,注意字段名称是区分大小写的
                    fields.setField(key, value);
                }
                //民族
                Dict nationDict = dictMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getCode, partTimeManagement.getNationId()));
                fields.setField("nation", nationDict.getName());
                //健康状况
                Dict healthConditionDict = dictMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getCode, partTimeManagement.getHealthConditionId()));
                fields.setField("healthCondition", healthConditionDict.getName());
                //全职学位
                fields.setField("fulltimeDegree", partTimeManagement.getFulltimeDegree());
                fields.setField("fulltimeSchoolMajor", partTimeManagement.getFulltimeSchoolMajor());
                //在职学位
                fields.setField("onjobDegree", partTimeManagement.getOnjobDegree());
                fields.setField("onjobSchoolMajor", partTimeManagement.getOnjobSchoolMajor());

                List<PartTimeInfo> allPartTimeInfos = partTimeInfoMapper.selectList(new LambdaQueryWrapper<PartTimeInfo>().eq(PartTimeInfo::getStaffNameId, partTimeManagement.getStaffNameId()));
                if (CollectionUtil.isNotEmpty(allPartTimeInfos)) {
                    /**
                     * 已兼职情况
                     */
                    List<PartTimeInfo> yjzPartTimeInfos = allPartTimeInfos.stream().filter(item ->
                            item.getStatus().equals(PartTimeStatus.INCUMBENCY.getStatus())).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(yjzPartTimeInfos)) {
                        StringBuffer sb = new StringBuffer();
                        yjzPartTimeInfos.forEach(item -> {
                            if (StringUtils.isNotEmpty(item.getPartTimeEnterpriseName())) {
                                sb.append(item.getPartTimeEnterpriseName() + "  ");
                            }
                            if (StringUtils.isNotEmpty(item.getProposedConcurrentPost())) {
                                sb.append(item.getProposedConcurrentPost());
                            }
                            sb.append("\n");
                        });
                        //已兼职情况
                        fields.setField("parttimeJobSituation", sb.toString());

                        //意见
                        fields.setField("companyPartyOrgOpinion", yjzPartTimeInfos.get(0).getCompanyPartyOrgOpinion());
                        fields.setField("approvedOpinion", yjzPartTimeInfos.get(0).getApprovedOpinion());
                        fields.setField("gzRegulationOpinion", yjzPartTimeInfos.get(0).getGzRegulationOpinion());

                    }

                    /**
                     * 拟兼职
                     */
                    List<PartTimeInfo> partTimeInfos = allPartTimeInfos.stream().filter(item
                            -> item.getStatus().equals(PartTimeStatus.AUDIT.getStatus())).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(partTimeInfos)) {
                        String partTimeJobTimeStr = "";
                        String proposedConcurrentPost = "";
                        String parttimeJobReason = "";
                        for (PartTimeInfo partTimeInfo : partTimeInfos) {
                            if (Optional.ofNullable(partTimeInfo.getPartTimeStartTime()).isPresent() && Optional.ofNullable(partTimeInfo.getPartTimeEndTime()).isPresent()) {
                                String startStr = DateUtil.formatDate(partTimeInfo.getPartTimeStartTime());
                                String endStr = DateUtil.formatDate(partTimeInfo.getPartTimeEndTime());
                                if (StringUtil.isBlank(partTimeJobTimeStr)) {
                                    partTimeJobTimeStr += startStr + "~" + endStr;
                                } else {
                                    partTimeJobTimeStr += "，" + startStr + "~" + endStr;
                                }
                            }

                            if (Optional.ofNullable(partTimeInfo.getPartTimeEnterpriseName()).isPresent() && Optional.ofNullable(partTimeInfo.getProposedConcurrentPost()).isPresent()) {
                                if (StringUtil.isBlank(proposedConcurrentPost)) {
                                    proposedConcurrentPost += partTimeInfo.getPartTimeEnterpriseName() + partTimeInfo.getProposedConcurrentPost();
                                } else {
                                    proposedConcurrentPost += "，" + partTimeInfo.getPartTimeEnterpriseName() + partTimeInfo.getProposedConcurrentPost();
                                }
                            }

                            if (Optional.ofNullable(partTimeInfo.getPartTimeJobReason()).isPresent()) {
                                if (StringUtil.isBlank(parttimeJobReason)) {
                                    parttimeJobReason += partTimeInfo.getPartTimeJobReason();
                                } else {
                                    parttimeJobReason += "，" + partTimeInfo.getPartTimeJobReason();
                                }
                            }

                        }
                        fields.setField("proposedConcurrentPost", proposedConcurrentPost);
                        fields.setField("parttimeJobTime", partTimeJobTimeStr);
                        fields.setField("parttimeJobReason", parttimeJobReason);

                        //意见
                        fields.setField("companyPartyOrgOpinion", partTimeInfos.get(0).getCompanyPartyOrgOpinion());
                        fields.setField("approvedOpinion", partTimeInfos.get(0).getApprovedOpinion());
                        fields.setField("gzRegulationOpinion", partTimeInfos.get(0).getGzRegulationOpinion());

                    }
                }
                ps.setFormFlattening(true);
                ps.close();
                File dir = new File(model.getParent());
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(pdfName, "UTF-8"));
                response.setHeader("content-Type", "application/pdf");

                file = File.createTempFile("part_time_management", ".pdf", dir);
                OutputStream fos = response.getOutputStream();
                fos.write(bos.toByteArray());
                fos.flush();
                fos.close();
                bos.close();
            }

        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return file;
    }
}
